package com.torches.cloud.controller;

import com.torches.cloud.entities.FileEntity;
import com.torches.cloud.entities.Msg;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.FileFileFilter;
import org.apache.commons.io.filefilter.SuffixFileFilter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author torches
 */

@RestController
@RequestMapping("/disk")
public class DiskController {

    /**
     * 读取配置文件的云盘的基础目录
     */
    @Value("${cloudDisk.baseDir}")
    private String cloudDiskBaseDir;

    @RequestMapping("/download")
    public Msg downloadFile(HttpServletResponse response,
                            @RequestParam("username") String username,
                            @RequestParam("downloadPath") String filePath) throws UnsupportedEncodingException {
        String fileName = FileEntity.getFileNameFormUrl(filePath);
        System.out.println("下载文件" + fileName);
        // 设置头部信息
        response.setContentType("text/html;charset=utf-8");
        response.setHeader("content-type", "application/octet-stream");
        response.setHeader("content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

        HttpStatus status = HttpStatus.OK;
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            System.out.println("下载：" + cloudDiskBaseDir + File.separator + username + filePath.replace("/",File.separator));
            FileUtils.copyFile(new File(cloudDiskBaseDir + File.separator + username + filePath), outputStream);

        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    @PostMapping("/upload")
    public Msg uploadFile(@RequestParam MultipartFile file,
                          @RequestParam("username") String username,
                          @RequestParam("uploadPath") String path) throws IOException {

        String filename = file.getOriginalFilename();
        System.out.println("上传" + filename);
        String filePth = cloudDiskBaseDir +  File.separator + username + path + File.separator  + filename;
        System.out.println(filePth);
        System.out.println(filePth);
        InputStream is = file.getInputStream();
        OutputStream os = new FileOutputStream(new File(filePth));
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = is.read(buffer)) != -1) {
            os.write(buffer, 0, len);
        }
        os.close();
        is.close();
        return Msg.getMsg(100, "上传成功");
    }

    // 获取指定目录的文件及文件夹
    @PostMapping("/getFileList")
    public Msg getFileList(@RequestBody() Map<String,String> map) {
        // 获取用户名
        String username = map.get("username");
        // 获取路径
        String path = map.get("path");
        System.out.println(username + path);
        // 实际路径 = 云盘的基本路径 + 用户名 + 路径
        String realPath = cloudDiskBaseDir + File.separator + username + path;
        // 根据操作系统跟分隔符(window搞特殊)
        realPath = realPath.replace('/', File.separator.charAt(0));

        // 根据路径的生成File对象
        File queryFile = new File(realPath);

        // 获取该目录下的所有文件和目录
        List<File> files = Arrays.asList(queryFile.listFiles());
        // 日期格式化类
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm");
        // 得到我们需要的类型
        ArrayList<FileEntity> fileEntities = new ArrayList<>();
        // 得到我们需要的类型
        ArrayList<FileEntity> folderEntities = new ArrayList<>();

        // 用户文件的相对路径
        String relativeBaseDir = "/".equals(path) ? "" : path;
        for (File fileItem : files) {
            // new 自定义数据类fileEntity
            FileEntity fileEntity = new FileEntity(fileItem.getName(),
                    relativeBaseDir + "/" + fileItem.getName(),
                    sdf.format(fileItem.lastModified()),
                    fileItem.isDirectory(),
                    fileItem.length());
            if (fileItem.isDirectory()){
                folderEntities.add(fileEntity);
            }else {
                fileEntities.add(fileEntity);
            }
        }

        folderEntities.addAll(fileEntities);

        return Msg.getMsg(200, "获取成功").addData("fileList", folderEntities);
    }

    @RequestMapping("/deleteFile")
    public Msg deleteFile(@RequestBody() Map<String,String> map){
        System.out.println(map);
        String path = cloudDiskBaseDir + File.separator + map.get("username") + map.get("deleteFolderPath");
        path = path.replace("/",File.separator);
        System.out.println(path);
        File deleteFolderFile = new  File(path);
        if (deleteFolderFile.exists()){
            deleteFolderFile.delete();
        }
        return Msg.getMsg(100, "删除成功");
    }

    @RequestMapping("/createFolder")
    public Msg createFolder(@RequestBody() Map<String,String> map){
        System.out.println(map);
        String newFolderPath = map.get("newFolderPath");
        String path = cloudDiskBaseDir + File.separator + map.get("username") + map.get("newFolderPath");
        path = path.replace("/",File.separator);
        System.out.println(path);
        File newFolderFile = new  File(path);
        if (newFolderFile.exists()){
            System.out.println("文件已存在");
        } else {
            System.out.println("创建文件夹");
            newFolderFile.mkdir();
        }

        return Msg.getMsg(100, "创建文件夹成功");
    }

}
